package com.itwzy.bookshop.controller;

import com.itwzy.bookshop.Bean.BookBean;
import com.itwzy.bookshop.Bean.PageBean;
import com.itwzy.bookshop.Bean.ResultBean;
import com.itwzy.bookshop.DAO.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BookController {
    @Autowired
    private BookDao bookDao;

    /**
     * 添加图书
     * @param book
     * @return
     */
    @RequestMapping("/save_book")
    public ResultBean saveBook(BookBean book){
        ResultBean result = new ResultBean();
        if(bookDao.insertBook(book)==1){
            result.setCode(1);
            result.setMsg("图书添加成功");
        }else {
            result.setCode(-1);
            result.setMsg("图书添加失败");
        }
        return result;
    }

    /**
     * 分页查询图书
     * @param pageNow
     * @return
     */
    @RequestMapping("/get_books_page")
    public ResultBean getBookPage(Integer pageNow){
        ResultBean result = new ResultBean();
        PageBean page = new PageBean();
        page.setRowCount(bookDao.getRowCount());
        page.setPageCount(page.getRowCount()%page.getPageSize()==0
                           ?page.getRowCount()/page.getPageSize()
                           :page.getRowCount()/page.getPageSize() + 1);
        page.setPageNow(pageNow == null?1:
                pageNow<1?1:
                pageNow>page.getPageCount()?page.getPageCount():pageNow);
        List<BookBean> books = bookDao.selectBooksPage(page);

        Map<String,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("books",books);

        result.setCode(1);
        result.setData(map);
        return result;
    }

    /**
     * 删除图书
     * @param bookId
     * @return
     */
    @RequestMapping("/drop_book")
    public ResultBean dropBook(Integer bookId){
        ResultBean result = new ResultBean();
        if (bookDao.deleteBook(bookId)==1){
            result.setCode(1);
            result.setMsg("删除图书成功");
        }else {
            result.setCode(-1);
            result.setMsg("删除图书失败");
        }
        return result;
    }

    /**
     * 修改图书
     * @param book
     * @return
     */
    @RequestMapping("/edit_book")
    public ResultBean editBook(BookBean book){
        ResultBean result = new ResultBean();
        if (bookDao.updateBook(book)==1){
            result.setCode(1);
            result.setMsg("修改图书成功");
        }else {
            result.setCode(-1);
            result.setMsg("修改图书失败");
        }
        return result;
    }
}
